//
//  NewsVC.m
//  Brand
//
//  Created by Faker on 4/21/14.
//  Copyright (c) 2014 Faker. All rights reserved.
//

#import "NewsVC.h"
#import "NewsObj.h"
#import "NewsDetailVC.h"
#import "config.h"
#import "Header.h"

#define NumsOfCellInEveryPage    10

@interface NewsVC ()
@property (weak, nonatomic) IBOutlet UIView *navTopContentView;
@property (weak, nonatomic) IBOutlet UITableView *myTableView;

@property (strong, nonatomic) NSMutableArray* dataArray;


@property (strong, nonatomic) DropLoadingView* dropLoadingView;
@property (strong, nonatomic) LoadingTipsView* loadingTipsView;

@property (assign, nonatomic) int totalPages;
@property (assign, nonatomic) int firstPageCells;

@end

@implementation NewsVC

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(void)viewWillAppear:(BOOL)animated
{
//    if(self.dropLoadingView)
//    {
//        [self.dropLoadingView hasCancelRequestAndRestore];
//    }
//    if(self.loadingTipsView)
//    {
//        [self.loadingTipsView otherPageLoadFailed];
//    }
    
    [self.myTableView reloadData];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self drawNavTopContentView:self.navTopContentView];
    self.dataArray = [NSMutableArray array];
    self.dropLoadingView = [[DropLoadingView alloc]initWithParentView:self.myTableView andDelegate:self];
    self.loadingTipsView = [[LoadingTipsView alloc]init];
    self.loadingTipsView.delegate = self;
    
    [self prepareGetData];
}

#pragma mark - 数据请求
-(void)prepareGetData
{
    [kApp displayWaitViewWithAllMaskView:NO];
    NSString* url = [NSString stringWithFormat:@"%@newsList",API_BASE];
   
    [[AFGetData sharedInstance] startGet:url andResultIsJSON:YES andRequestCompletion:^(id responseObj, BOOL isSuccess) {
        if(isSuccess)
        {
            [self getDataSuccessWithData:responseObj];
        }
        else{
            [self getDataError];
        }
    }];
}

-(void)getDataSuccessWithData:(id)responseObj
{
    [kApp hideWaitView];
    [self.dataArray removeAllObjects];
    [self getTotalPagesAndFistPageCellsWith:responseObj];
    [self dicToObjWithArray:responseObj];
    [self handleData];
    [UserDataBasic saveThisObjectArray:self.dataArray forArrayKey:LocalNewsData];
    [self.dropLoadingView hasGetDataOverAndRestore];
}

-(void)getDataError
{
    [kApp hideWaitView];
    [PopTips tips:self.view Msg:NotifyNoNet];
    
    if([self.dataArray count] !=0) //内存中有数据
    {
        
    }
    
    else
    {
        self.dataArray = [UserDataBasic readObjectArrayForKey:LocalNewsData];
        if([self.dataArray count] != 0)
        {
            [self getTotalPagesAndFistPageCellsWith:self.dataArray];
           [self handleData];
        }
        else{
        
            [self performSelector:@selector(goBack:) withObject:self afterDelay:0.7];
            return;

        }
    }
    [self.dropLoadingView hasGetDataOverAndRestore]; //其实就是归位
}

-(void)getTotalPagesAndFistPageCellsWith:(id)responseObj
{
    NSArray* tempArray = (NSArray*)responseObj;
    
    int totalNums = [tempArray count];
    
    if(totalNums<10)
    {
        self.totalPages = 1;
        self.firstPageCells = totalNums;
    }
    else{
        self.firstPageCells = NumsOfCellInEveryPage;
        self.totalPages = totalNums/NumsOfCellInEveryPage;
        if(totalNums%NumsOfCellInEveryPage)
        {
            self.totalPages++;
        }
    }
    
}

-(void)dicToObjWithArray:(NSArray*)tempArray
{
    for (int i = 0; i<self.firstPageCells; i++) {
        NSDictionary* cur = [tempArray objectAtIndex:i];
        NewsObj* newsObj = [[NewsObj alloc]init];
        newsObj.mId = [cur objectForKey:@"id"];
        newsObj.title = [cur objectForKey:@"title"];
        newsObj.date = [cur objectForKey:@"date"];
        newsObj.source = [cur objectForKey:@"source"];
        newsObj.pic = [cur objectForKey:@"pic"];
        newsObj.url = [cur objectForKey:@"url"];
        [self.dataArray addObject:newsObj];
    }

}

-(void)handleData
{
    NSLog(@"pages = %d",self.totalPages);
    [self.myTableView reloadData];
    [self.loadingTipsView drawNowInParentView:self.myTableView andTotalPage:self.totalPages];

}

#pragma mark - DropLoadingViewDelegate
-(void)dropLoadingViewStartGetData:(DropLoadingView *)dropLoadingView
{
    [self prepareGetData];
}

#pragma mark - LoadingTipsViewDelegate
-(void)loadingTipsView:(LoadingTipsView *)loadingTipsView startLoadThePage:(int)page
{
    NSString* url = [NSString stringWithFormat:@"%@newsList&page=%d&perpage=%d",API_BASE,page,NumsOfCellInEveryPage];
    [[AFGetData sharedInstance] startGet:url andResultIsJSON:YES andRequestCompletion:^(id responseObj, BOOL isSuccess) {
        if(isSuccess)
        {
            [self getOtherDataSuccess:responseObj];
        }
        else{
            [self getOtherDataError];
        }
    }];
}

-(void)getOtherDataSuccess:(id)responseObj
{
    NSArray* tempArray = (NSArray*)responseObj;
    for (NSDictionary* cur in tempArray) {
        NewsObj* newsObj = [[NewsObj alloc]init];
        newsObj.mId = [cur objectForKey:@"id"];
        newsObj.title = [cur objectForKey:@"title"];
        newsObj.date = [cur objectForKey:@"date"];
        newsObj.source = [cur objectForKey:@"source"];
        newsObj.pic = [cur objectForKey:@"pic"];
        newsObj.url = [cur objectForKey:@"url"];
        [self.dataArray addObject:newsObj];
    }
    [self.myTableView reloadData];
    [self.loadingTipsView otherPageLoadSuccess];
}

-(void)getOtherDataError
{
    [PopTips tips:self.view Msg:NotifyNoNet];
    [self.loadingTipsView otherPageLoadFailed];
    
}

#pragma mark - UITableViewDelegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString* identifier = @"identifier";
    UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if(cell == nil)
    {
        cell = [[[NSBundle mainBundle]loadNibNamed:@"NewsCell" owner:self options:nil]lastObject];
    }
    
    UILabel* timeLabel = (UILabel*)[cell viewWithTag:202];
    UILabel* nameLabel = (UILabel*)[cell viewWithTag:200];
    UILabel* fromLabel = (UILabel*)[cell viewWithTag:203];
    UIImageView* imageView = (UIImageView*)[cell viewWithTag:302];
    UIImageView* newImageView = (UIImageView*)[cell viewWithTag:303];

    
    NewsObj* newsObj = [self.dataArray objectAtIndex:indexPath.row];
    NSMutableArray* tempArray = [UserDataBasic readObjectArrayForKey:LocalOldNewsData];
    for (NewsObj* oldNews in tempArray) {
        if([newsObj.mId isEqualToString:oldNews.mId])
        {
            newImageView.hidden = YES; //已读
            break;
        }
        else{
            newImageView.hidden  = NO;
        }
    }
    
    
    timeLabel.text = newsObj.date;
    fromLabel.text = newsObj.source;
    [Common handleTheLabelHeight:nameLabel withText:newsObj.title];
   
    [[AFGetData sharedInstance] initSDWebImage:newsObj.pic andTrueImageView:imageView andPlaceholderImage:nil];
    
    cell.backgroundColor = [UIColor clearColor];
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 109;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NewsDetailVC* detailVC = [[NewsDetailVC alloc]initWithNibName:@"NewsDetailVC" bundle:nil];
    NewsObj* newsObj = [self.dataArray objectAtIndex:indexPath.row];
    
    //detailVC.url = newsObj.url;
    detailVC.title = @"最新资讯";
    NSDictionary* dic = [NSDictionary dictionaryWithObjectsAndKeys:newsObj.url,@"url", nil];
    NSArray* dataArrray = [NSArray arrayWithObjects:dic, nil];
    detailVC.dataArray = dataArrray;
    
    NSMutableArray* tempArray = [UserDataBasic readObjectArrayForKey:LocalOldNewsData];
    [tempArray addObject:newsObj];
    [UserDataBasic saveThisObjectArray:tempArray forArrayKey:LocalOldNewsData];
    
    [self.navigationController pushViewController:detailVC animated:YES];
    [Common getWYByPostWithType:@"3" andItemId:@"0"];
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [self.dropLoadingView onScroll];
    [self.loadingTipsView onScroll];
}

-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    [self.dropLoadingView endDraing];
    [self.loadingTipsView endDraing];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (IBAction)goBack:(id)sender {
    [[AFGetData sharedInstance] removeAllGetAndPostRequest];
    [self.navigationController popViewControllerAnimated:YES];
}



@end
